<?php

namespace common\widgets\grid;

use Yii;
use yii\helpers\Html;
use yii\helpers\ArrayHelper;

/**
 * PortletColumn displays a column of mark text content in a grid view.
 *
 * @author emhome <emhome@163.com>
 * @since 2.0
 */
class CombineColumn extends DataColumn {

    public $format = 'raw';

    /**
     * @var string the attribute name associated with this column. When neither [[content]] nor [[value]]
     * is specified, the value of the specified attribute will be retrieved from each data model and displayed.
     *
     * Also, if [[label]] is not specified, the label associated with the attribute will be displayed.
     */
    public $combineAttribute;

    /**
     * @var array 组合单元格配置项
     */
    public $combineOptions = [];

    /**
     * {@inheritdoc}
     */
    protected function renderDataCellContent($model, $key, $index) {
        $first = Html::tag('div', parent::renderDataCellContent($model, $key, $index), [
            'class' => 'combine-first'
        ]);

        $seconed = Html::tag('div', $this->renderCombineCellContent($model, $key, $index), [
            'class' => 'combine-seconed'
        ]);
        $options = ArrayHelper::getValue($this->combineOptions, 'options', []);
        Html::addCssClass($options, 'combin');
        return Html::tag('div', $first . $seconed, $options);
    }

    /**
     * Returns the data cell value.
     * @param mixed $model the data model
     * @param mixed $key the key associated with the data model
     * @param int $index the zero-based index of the data model among the models array returned by [[GridView::dataProvider]].
     * @return string the data cell value
     */
    public function getCombineCellValue($model, $key, $index) {
        $options = $this->combineOptions;
        $value = ArrayHelper::getValue($options, 'value');
        if ($value !== null) {
            if (is_string($value)) {
                return ArrayHelper::getValue($model, $value);
            }
            return call_user_func($value, $model, $key, $index, $this);
        } elseif ($this->combineAttribute !== null) {
            return ArrayHelper::getValue($model, $this->combineAttribute);
        }
        return null;
    }

    /**
     * 输出组合内容
     * @param mixed $model
     * @param mixed $key
     * @param array $index
     * @return type
     */
    protected function renderCombineCellContent($model, $key, $index) {
        $options = $this->combineOptions;
        $content = ArrayHelper::getValue($options, 'content');
        $format = ArrayHelper::getValue($options, 'format', 'text');
        if ($content === null) {
            return $this->grid->formatter->format($this->getCombineCellValue($model, $key, $index), $format);
        }
        return call_user_func($content, $model, $key, $index, $this);
    }

}
